package controllers

import (
	"centerServer/compnents"
	"centerServer/models"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type LingQianFuKunController struct {
	beego.Controller
}

func (this *LingQianFuKunController) Get() {
	requestInfo := models.LingQianRequest{}
	backMsg := models.CreatorBackBase(0, "")
	if err := this.ParseForm(&requestInfo); err != nil {
		//handle error
		backMsg.ReturnCode = -1
		backMsg.Msg = "参数解析错误" + err.Error()
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	// 检测签名
	checkSignMap := requestInfo.GetSignInfos()
	if compnents.CheckSign(checkSignMap, requestInfo.Sign) == false {
		backMsg.ReturnCode = -1
		backMsg.Msg = "签名错误"
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	// 创建存储信息结构
	saveData := models.BonusLingQianDataModel{}
	saveData.FillRequestData(&requestInfo)
	// 检测是否重复订单
	if saveData.IsExsit() {
		backMsg.ReturnCode = -1
		backMsg.Msg = "重复订单"
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	// 检测时间戳,只处理时间戳在30s以内的
	//if time.Now().Unix()-requestInfo.RequestTime >= 30 {
	//	backMsg.ReturnCode = -1
	//	backMsg.Msg = "订单超时"
	//	backData, _ := json.Marshal(backMsg)
	//	this.Ctx.Output.Body(backData)
	//	return
	//}
	isOK, errL := compnents.GetWxLingQianCompnent().SendBonus(requestInfo.OpenId, requestInfo.Amount, requestInfo.MchAppId, &saveData)
	if errL == nil && isOK{
		saveData.SetSuccess(isOK)
		saveData.WriteToDB()
	} else {
		logs.Error("LingQianFuKunController err" + errL.Error())
		backMsg.ReturnCode = -1
		backMsg.Msg = "微信接口错误"
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	backData, _ := json.Marshal(backMsg)
	this.Ctx.Output.Body(backData)
}
